package com.yzh.wanandroid.component.fragment

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yzh.wanandroid.R
import com.yzh.wanandroid.adapter.ArticleListAdapter
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.databinding.FragmentHomePagerBinding
import com.yzh.wanandroid.utils.SUCCESS
import com.yzh.wanandroid.vm.HomePagerFragmentVm
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class HomePagerFragment : MvvmFragment<FragmentHomePagerBinding, HomePagerFragmentVm>() {

    private val adapter by lazy { ArticleListAdapter() }

    override fun getLayoutId() = R.layout.fragment_home_pager

    override fun initViewModel(): HomePagerFragmentVm = createViewModel()

    companion object {
        fun getInstance() = HomePagerFragment()
    }

    override fun initView(view: View) {
        initRecyclerView()
        initSwipeRefresh()
    }

    override fun initData() {
        initBinding()
    }

    override fun onLazyLoad() {
        super.onLazyLoad()
        loadArticleData()
        loadBanner()
    }

    private fun initBinding() {
        mBinding.run {
            netWorkData = mViewModel.netWorkData
            articleListAdapter = adapter
            refreshData = adapter.refreshData
            homePagerFragment = this@HomePagerFragment
        }
    }

    private fun initRecyclerView() {
        mBinding.run {
            var linearLayoutManager = LinearLayoutManager(requireActivity())
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            articleList.layoutManager = linearLayoutManager
        }
    }

    /**
     * 初始化 SwipeRefreshLayout
     */
    private fun initSwipeRefresh() {
        mBinding.run {
            articleSwipeRefresh.setColorSchemeResources(R.color.color_main)
            articleSwipeRefresh.setOnRefreshListener { initData() }
        }
    }

    /**
     *  加载文章
     */
    private fun loadArticleData() {
        lifecycleScope.launch {
            try {
                mViewModel.getData().collectLatest {
                    adapter.submitData(it)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 加载首页banner
     */
    private fun loadBanner() {
        mViewModel.loadingBanner.observe(this) {
            when (it.loadingState) {
                SUCCESS -> it.data?.let { it1 -> adapter.setBannerData(it1) }
            }
        }
    }

    /**
     * 点击重新加载按钮
     */
    fun onReloadClick() {
        mViewModel.checkNetData()
        loadArticleData()
        mViewModel.loadTopBanner(this)
    }
}